<template>
  <a-modal
    :visible="visible"
    @update:visible="handleVisibleChange"
    title="我的战队"
    width="800px"
    @cancel="handleCancel"
    :maskClosable="false"
  >
    <div class="my-teams-container">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <a-spin size="large" />
        <p>加载中...</p>
      </div>

      <!-- 空状态 -->
      <div v-else-if="teams.length === 0" class="no-teams">
        <div class="empty-icon">
          <i class="fa fa-users" />
        </div>
        <p>你还没有加入任何战队</p>
        <a-button type="primary" @click="goToTeamHall">
          <i class="fa fa-plus mr-2"></i>去组队大厅
        </a-button>
      </div>

      <!-- 战队列表 -->
      <div v-else class="teams-list">
        <a-row :gutter="[16, 16]">
          <a-col :xs="24" :sm="12" :md="8" v-for="team in teams" :key="team.id">
            <a-card hoverable class="my-team-card" @click="viewTeamDetail(team.id)">
              <template #cover>
                <img
                  :src="getTeamLogoUrl(team.logo)"
                  :alt="team.teamName"
                  class="team-logo"
                  @error="handleImageError"
                >
              </template>
              <div class="team-info">
                <h4 class="team-name">{{ team.teamName }}</h4>
                <p class="team-creator">创建人: {{ team.username  }}</p>

                <div class="team-meta">
                  <a-tag :color="team.needReview === 1 ? 'orange' : 'green'" class="review-tag">
                    {{ team.needReview === 1 ? '需要审核' : '无需审核' }}
                  </a-tag>
                  <span class="member-count">{{ team.currentCount || 0 }}/{{ team.maxCount }}人</span>
                </div>

                <div class="team-tags" v-if="team.tagList && team.tagList.length">
                  <a-tag v-for="tag in team.tagList" :key="tag" color="blue" class="team-tag">
                    {{ tag }}
                  </a-tag>
                </div>

                <div class="team-actions">
                  <a-button
                    type="link"
                    @click.stop="leaveTeam(team.id)"
                    class="leave-btn"
                  >
                    退出战队
                  </a-button>
                </div>
              </div>
            </a-card>
          </a-col>
        </a-row>
      </div>
    </div>
  </a-modal>
</template>

<script setup>
import { ref, defineProps, defineEmits, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { quitTeam, selectMyAllTeams } from '@/api/sysTeamController.js' // 导入你的接口
// import { exitTeam } from '@/api/sysTeamController'; // 假设退出战队接口
import { getMinioUrl, config } from '@/utils/config';


const router = useRouter();

// 组件属性
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});

// 组件事件
const emit = defineEmits(['update:visible', 'onClose']);

// 状态管理
const loading = ref(false);
const teams = ref([]); // 存储我的战队列表

// 标签映射表（与你的业务标签对应）
const tagMap = {
  '1': '前端', '2': 'Vue', '3': 'React', '4': 'Java', '5': 'Spring', '6': '后端',
  '7': 'Python', '8': '数据分析', '9': '机器学习', '10': '移动开发', '11': 'Android', '12': 'iOS'
};

// 检查用户登录状态
const checkUserLogin = () => {
  try {
    const storedUserInfo = localStorage.getItem('userInfo');
    return storedUserInfo ? JSON.parse(storedUserInfo) : null;
  } catch (error) {
    console.error('检查用户登录状态失败:', error);
    return null;
  }
};

// 获取用户ID
const getLoginIdAsInt = () => {
  const userInfo = checkUserLogin();
  return userInfo && userInfo.userId ? parseInt(userInfo.userId) : null;
};

// 处理标签格式（将逗号分隔的tag转为标签名数组）
const processTags = (tagStr) => {
  if (!tagStr) return [];
  return tagStr.split(',').map(tagId => tagMap[tagId] || `标签${tagId}`);
};

// 获取我的战队列表（调用接口）
const fetchJoinedTeams = async () => {
  const userId = getLoginIdAsInt();
  if (!userId) {
    message.warning('请先登录');
    emit('update:visible', false);
    return;
  }

  loading.value = true;
  try {
    // 调用接口，传入用户ID参数
    const response = await selectMyAllTeams();
    console.log(response)
    if (response.data.code === 0) {
      // 处理接口返回的数据
      teams.value = response.data.data.map(team => ({
        ...team,
        tagList: processTags(team.tag), // 转换标签格式
        currentCount: team.currentCount || 0 // 兼容可能缺失的人数字段
      }));
    } else {
      message.error(response.data.message || '获取我的战队失败');
      teams.value = [];
    }
  } catch (error) {
    console.error('获取我的战队失败:', error);
    message.error('网络错误，获取战队列表失败');
    teams.value = [];
  } finally {
    loading.value = false;
  }
};

// 处理弹窗显示状态变化
const handleVisibleChange = (newVisible) => {
  emit('update:visible', newVisible);
};

// 关闭弹窗
const handleCancel = () => {
  emit('update:visible', false);
  emit('onClose');
};

// 查看战队详情
const viewTeamDetail = (teamId) => {
  emit('update:visible', false);
  router.push({ path: '/team', query: { teamId } });
};

// 退出战队
const leaveTeam = async (teamId) => {
  const userId = getLoginIdAsInt();
  if (!userId) {
    message.warning('请先登录');
    return;
  }

  try {
    const response = await quitTeam({
      teamId
    });

    if (response.data.code === 0) {
      message.success('已成功退出战队');
      await fetchJoinedTeams(); // 重新获取战队列表
    } else {
      message.error(response.data.message || '退出战队失败');
    }
  } catch (error) {
    console.error('退出战队失败:', error);
    message.error('网络错误，退出战队失败');
  }
};

// 前往组队大厅
const goToTeamHall = () => {
  emit('update:visible', false);

    router.push('/teamLearningPlatform');
};

// 获取战队Logo URL
const getTeamLogoUrl = (logo) => {
  if (!logo) return config.image.defaultLogo;
  return getMinioUrl(logo) || config.image.defaultLogo;
};

// 图片加载错误处理
const handleImageError = (event) => {
  event.target.src = config.image.defaultLogo;
};

// 监听弹窗显示状态，自动加载数据
watch(() => props.visible, (newVal) => {
  if (newVal) {
    fetchJoinedTeams(); // 弹窗显示时加载数据
  }
});

// 组件挂载时如果可见，加载数据
onMounted(() => {
  if (props.visible) {
    fetchJoinedTeams();
  }
});
</script>

<style scoped>
/* 保持原样式不变，可根据需要微调 */
.my-teams-container {
  max-height: 600px;
  overflow-y: auto;
  padding-right: 8px;
}

.loading-container {
  text-align: center;
  padding: 40px 0;
  color: #666;
}

.no-teams {
  text-align: center;
  padding: 40px 0;
  color: #666;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #ccc;
}

.teams-list {
  margin-top: 16px;
}

.my-team-card {
  height: 100%;
  cursor: pointer;
  transition: all 0.3s ease;
}

.my-team-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.team-logo {
  width: 100%;
  height: 160px;
  object-fit: cover;
}

.team-info {
  padding: 12px;
}

.team-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.team-creator {
  font-size: 13px;
  color: #666;
  margin-bottom: 12px;
}

.team-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-size: 12px;
}

.member-count {
  color: #666;
}

.team-tags {
  margin-bottom: 12px;
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.team-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 8px;
}

.leave-btn {
  color: #f5222d !important;
  padding: 0 !important;
  font-size: 13px;
}

.leave-btn:hover {
  color: #cf1322 !important;
  text-decoration: underline;
}
</style>
